package com.lcz.licence.util;

import com.lcz.licence.entity.LicenseCreatorParam;
import com.lcz.licence.serverinfo.CustomKeyStoreParam;
import de.schlichtherle.license.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.util.prefs.Preferences;

/**
 * @author lcz
 * @desc 证书生成器
 * @mail lcz_0130@163.com
 * @date 2025/07/21
 */
@Data
@Slf4j
public class LicenseCreator {

    static X500Principal DEFAULT_HOLDER_AND_ISSUER = new X500Principal("CN=keepc, OU=keepc, O=keepc, L=KC, ST=KC, C=CN");

    private LicenseCreatorParam param;

    public LicenseCreator(LicenseCreatorParam param) {
        this.param = param;
    }

    /**
     * 生成License证书
     */
    public boolean generateLicense() {
        try {
            KeyStoreGenerator keyStoreGenerator = new KeyStoreGenerator(param);
            keyStoreGenerator.generateAndImportKeys();


            LicenseManager licenseManager = new LicenseManager(initLicenseParam());
            LicenseContent licenseContent = initLicenseContent();

            licenseManager.store(licenseContent, new File(param.getLicensePath()));

            return true;
        } catch (Exception e) {
            log.error("证书生成失败：{}", param, e);
            return false;
        }
    }

    /**
     * 初始化证书生成参数
     */
    private LicenseParam initLicenseParam() {
        Preferences preferences = Preferences.userNodeForPackage(LicenseCreator.class);
        // 设置对证书内容加密的秘钥
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam privateStoreParam = new CustomKeyStoreParam(LicenseCreator.class,
                param.getPrivateKeysStorePath(), param.getPrivateAlias(),
                param.getStorePass(), param.getKeyPass());
        return new DefaultLicenseParam(param.getSubject(), preferences,
                privateStoreParam, cipherParam);
    }

    /**
     * 设置证书生成正文信息
     */
    private LicenseContent initLicenseContent() {
        LicenseContent licenseContent = new LicenseContent();
        licenseContent.setHolder(DEFAULT_HOLDER_AND_ISSUER);
        licenseContent.setIssuer(DEFAULT_HOLDER_AND_ISSUER);

        licenseContent.setSubject(param.getSubject());
        licenseContent.setIssued(param.getIssuedTime());
        licenseContent.setNotBefore(param.getIssuedTime());
        licenseContent.setNotAfter(param.getExpireTime());
        licenseContent.setConsumerType(param.getConsumerType());
        licenseContent.setConsumerAmount(param.getConsumerAmount());
        licenseContent.setInfo(param.getDescription());

//        if (null!=param.getAdditionInfo()){
            // 扩展校验服务器硬件信息
            licenseContent.setExtra(param.getAdditionInfo());
//        }

        return licenseContent;
    }
}
